package com.travel.service.impl;


import com.travel.config.MinioConfig;
import com.travel.service.MinioService;
import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Component
public class MinioServiceImpl implements MinioService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConfig minioConfig;

    /**
     * 查看存储bucket是否存在
     * @param bucketName 存储bucket
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return found;
    }

    /**
     * 创建存储bucket
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    @Override
    public String upload(MultipartFile file, String prefix) {
        return upload(file, minioConfig.getDefaultBucket(),prefix);
    }
    /**
     *
     * @param file multiPart 文件
     * @param bucketName 文件存储的bucket桶名称
     * @param prefix 文件在桶中的前缀
     * @return 文件的访问地址
     */
    @Override
    public String upload(MultipartFile file, String bucketName,String prefix) {
        if(!bucketExists(bucketName)){
            makeBucket(bucketName);
        }

        try {
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String fileName = UUID.randomUUID()+"."+suffix;
            if (prefix == null || prefix.isEmpty() || prefix.equals("/")) {
                fileName = "/" +fileName;
            } else {
                fileName = "/"+prefix+"/" + fileName;
            }

            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(),file.getSize(),-1)
                    .contentType(file.getContentType())
                    .build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
            return minioConfig.getEndpoint()+"/"+bucketName +fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @Override
    public String uploadBytes(InputStream file, String contentType, String bucketName, String prefix) {
        if(!bucketExists(bucketName)){
            makeBucket(bucketName);
        }
        try {
            String suffix = contentType.split("/")[1];
            String fileName = UUID.randomUUID()+"."+suffix;
            if (prefix == null || prefix.isEmpty() || prefix.equals("/")) {
                fileName = "/" +fileName;
            } else {
                fileName = "/"+prefix+"/" + fileName;
            }

            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName)
                    .object(fileName)
                    .stream(file, file.available(), -1)
                    .contentType(contentType)
                    .build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
            return minioConfig.getEndpoint()+"/"+bucketName +fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void download(String urlString, HttpServletResponse response){

        String regex = "https?://[^/]+/(.*)";
        // 创建 Pattern 对象
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(urlString);
        String result = "";
        if (matcher.find()) {
            // 提取并打印第三个斜线后的内容
            result = matcher.group(1);
        } else {
        }
        String[] results = result.split("/",2);
        download(results[0],results[1],response);
    }

    /**
     * 文件下载
     * @param bucketName 存储bucket名称
     * @param fileName 文件名称
     * @param res response
     * @return Boolean
     */
    public void download(String bucketName, String fileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                //设置强制下载不打开
                // res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看文件对象
     * @param bucketName 存储bucket名称
     * @return 存储bucket内文件对象信息
     */
    public List<JSONObject> listObjects(String bucketName) {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).build());
        List<JSONObject> objectItems = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                Item item = result.get();
                JSONObject objectItem = new JSONObject();
                objectItem.put("object_name",item.objectName());
                objectItem.put("size",item.size());
                objectItems.add(objectItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectItems;
    }

    /**
     * 批量删除文件对象
     * @param bucketName 存储bucket名称
     * @param objects 对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        return results;
    }

}
